package com.hkd.common.api;

import com.alibaba.fastjson.JSONObject;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * feign异常统一处理
 * @author HKD
 * @date 2022/9/11 0:00
 */
@Configuration
@Slf4j
public class ExceptionErrorDecoder extends ErrorDecoder.Default {

    @Override
    public Exception decode(String s, Response response) {
        try {
            String body = Util.toString(response.body().asReader(StandardCharsets.UTF_8));
            ExceptionInfo info = JSONObject.parseObject(body, ExceptionInfo.class);
            int status = response.status();
            //业务层扔出错误
            if (status == HttpStatus.BAD_REQUEST.value()) {
                return new SysException(info.getMessage());
            }
            return new RuntimeException(info.getMessage());
        } catch (Exception e) {
            return new ErrorDecoder.Default().decode(s, response);
        }
    }
}
